<?php
namespace wow\model;

use \gnomephp\doctrine\Doctrine;

/**
 * PayPal order is a database model that holds all data for a order.
 * @Entity
 */
class PayPalOrder extends \gnomephp\paypal\PayPalOrderModel{

	
	/**
	 * @ManyToOne(targetEntity="Donation")
     * @JoinColumn(name="donation_id", referencedColumnName="itemid")
	 */
	public $donation;
	
	
	/**
	 * @Column(type="integer")
	 */
	protected $user_id;
	
	/**
	 * @Column(type="integer")
	 */
	protected $char_id;
	
	/**
	 * @Column(type="integer")
	 */
	protected $realm_id;
	
	
	
	/**
	 * @Column(type="boolean")
	 */
	protected $item_recieved = false;
	
	
	public function __construct($txnId, $payerEmail, $mcGross, $mcCurrency, $donation, $userId, $char_id, $realm_id){
		parent::__construct($txnId, $payerEmail, $mcGross, $mcCurrency);
		$this->donation = $donation;
		$this->item_recieved = false;
		$this->user_id = $userId;
		$this->char_id = $char_id;
		$this->realm_id = $realm_id;
	}

	
	
	public function getMcGross(){
		return $this->mcGross;
	}
	public function getCurrency(){
		return $this->mcCurrency;
	}
	
	
	public function getUserId(){
		return $this->user_id;
	}
	
	public function getCharId(){
		return $this->char_id;
	}
	
	public function getRealmId(){
		return $this->realm_id;
	}
	
	public function getDonation(){
		return $this->donation;
	}
	
	public function setItemRecieved($recieved){
		$this->item_recieved = $recieved;
	}
	
	public function isItemRecieved(){
		return $this->item_recieved;
	}
	
	public function getUser(){
		return \wow\modelauth\Account::getUserById($this->user_id);
	}
	
	public function getCharacter(){
		return \wow\modelchar\Character::getCharacterById($this->realm_id, $this->char_id);
	}
	
	public function getRealm(){
		return \wow\modelauth\Realmlist::getRealmById($this->realm_id);
	}
	
	
	/**
	 * Checks if order is already processed.
	 * @param string $txnId TXN ID from paypal IPN.
	 */
	static public function orderProcessed($txnId){
		Doctrine::load();

		$q = Doctrine::getEM()->createQuery('SELECT p FROM wow\model\PayPalOrder p WHERE p.txnId = ?1')
		->setParameter(1, $txnId);

		if ($p = $q->getOneOrNullResult()){
			return $p;
		}else{
			return false;
		}

	}
	
	static public function getOrders(){
		Doctrine::load();
		$qb = Doctrine::getEM()->createQueryBuilder();
		$qb->select('n')
		->from('\wow\model\PayPalOrder', 'n')
		->orderBy('n.orderId', 'DESC');
		return $qb->getQuery()->getResult();
	}
	
	static public function getOrder($id){
		Doctrine::load();
		$q = Doctrine::getEM()->createQuery('SELECT n FROM \wow\model\PayPalOrder n WHERE n.orderId = ?1')->setParameter(1, $id);
		return $q->getOneOrNullResult();
	}

}